package com.cloudfun.campusshare.device.protocol.consumer;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.device.protocol.response.BaseMessage;
import com.cloudfun.campusshare.device.protocol.response.State;
import com.cloudfun.campusshare.service.DevicePropertyService;
import com.cloudfun.msgsubscribe.DeviceInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.Map;

/**
 * Created by Huqin on 2020/2/5
 */
@Slf4j
@Service
public class DeviceEventConsumer implements DeviceMessageConsumer {

    @Autowired
    private DevicePropertyService devicePropertyService;

    @Override
    public boolean support(Class<?> clazz) {
        return State.class.isAssignableFrom(clazz);
    }

    @Override
    public void doConsumer(BaseMessage message, String deviceName) {
        try {
            Map<?, ?> returnMap = BeanUtils.describe(message);
            returnMap.remove("class");
            returnMap.remove("ack");
            returnMap.remove("valid");
            returnMap.remove("timestamp");
            Map<String, String> properties = devicePropertyService.getDevicePropertiesByImei(deviceName);
            // 内部消费
            this.internalProcess(deviceName, message.getTimestamp(), properties, returnMap);
        } catch (Exception e) {
            log.error("设备状态处理异常：", e);
            throw new BusinessException(Code.SYSTEM_ERROR);
        }
    }

    private void internalProcess(String deviceName, String timestamp, Map<String, String> propertiesInDB, Map<?, ?> propertiesFromDevice) {
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setImei(deviceName);
        deviceInfo.setTimestamp(timestamp);
        for (Map.Entry<?, ?> entry : propertiesFromDevice.entrySet()) {
            String fieldName = (String) entry.getKey();
            String fieldValue = (String) entry.getValue();
            if (StringUtils.isBlank(fieldValue)) {
                continue;
            }
            // TODO 启动后立马停止，device_property里面的属性没有改变，导致设备状态未正确变化，cyclePhaseCD和cyclePhaseCW影响
            if (StringUtils.equals(fieldName, "cyclePhaseCD") || StringUtils.equals(fieldName, "cyclePhaseCW")) {
                deviceInfo.setAttr(fieldName, fieldValue);
                continue;
            }
            // 如果库中的值和解析出来的值一样 则跳过
            if (propertiesInDB.containsKey(fieldName) && propertiesInDB.get(fieldName).equals(fieldValue)) {
                continue;
            }
            deviceInfo.setAttr(fieldName, fieldValue);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("updateProperty: " + deviceName);
        // 内部消费
        devicePropertyService.updateProperty(deviceInfo);
        stopWatch.stop();
        log.info(stopWatch.prettyPrint());
    }

}
